package util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.*;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class AliDomainUtil {
    private IAcsClient client = null;
    private String accessKeyId;
    private String accessKeySecret;
    private String domain;
    private String recordId;
    private String hostRecoed;
//    主机记录就是域名前缀，常见用法有：
//    www：解析后的域名为www.aliyun.com。
//    @：直接解析主域名 aliyun.com。
//            *：泛解析，匹配其他所有域名 *.aliyun.com。
//    mail：将域名解析为mail.aliyun.com，通常用于解析邮箱服务器。
//    二级域名：如：abc.aliyun.com，填写abc。

//    private static String recordIp=null;

    public AliDomainUtil() {
        Properties properties = new Properties();
        InputStream in=this.getClass().getClassLoader().getResourceAsStream("config.properties");

        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

        accessKeyId = properties.getProperty("AccessKeyId");
        System.out.println("accessKeyId:"+ accessKeyId);
        accessKeySecret=properties.getProperty("AccessKeySecret");
        System.out.println("AccessKeySecret:"+accessKeySecret);
        domain=properties.getProperty("domain");
        System.out.println("domain:"+domain);
        hostRecoed=properties.getProperty("hostRecoed");
        System.out.println("hostRecoed:"+hostRecoed);

        String regionId = "cn-hangzhou"; //必填固定值，必须为“cn-hanghou”
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        // 若报Can not find endpoint to access异常，请添加以下此行代码
        // DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Alidns", "alidns.aliyuncs.com");
        client = new DefaultAcsClient(profile);
        getDnss();
    }

    public void getDnss(){
        String result = null;
        DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
        request.setDomainName(domain);
        request.setRRKeyWord(hostRecoed);

        try {
            DescribeDomainRecordsResponse response = client.getAcsResponse(request);
            result = new Gson().toJson(response);
            System.out.println(result);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        String RecordId = null;
        try {
            Map map = new Gson().fromJson(result, new TypeToken<Map>() {}.getType());
            List<Map> domainRecords = (List) map.get("domainRecords");
            RecordId = domainRecords.get(0).get("recordId").toString();
            System.out.println("RecordId:"+RecordId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.recordId = RecordId;
    }

    public String getRecordIp(){
        String recordIp = null;
        //获取域名当前解析
        try {
            InetAddress inetAddress= InetAddress.getByName(domain);
            recordIp = inetAddress.getHostAddress();
            System.out.println("当前域名解析ip："+recordIp);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return recordIp;
    }


    public String addDns(String ip){
        String result = null;
        AddDomainRecordRequest request = new AddDomainRecordRequest();

        request.setValue(ip);
        request.setType("A");
        request.setRR(hostRecoed);
        request.setDomainName(domain);

        try {
            AddDomainRecordResponse response = client.getAcsResponse(request);
            result=  new Gson().toJson(response) ;
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            return null;
        }

        JSONObject jsonObject = JSON.parseObject(result);
        String RecordId = jsonObject.getString("recordId");
        this.recordId = RecordId;
        return RecordId;
    }

    public Boolean updateDns(String ip){
        String result = null;
        UpdateDomainRecordRequest request = new UpdateDomainRecordRequest();

        request.setRecordId(this.recordId);
        request.setRR(hostRecoed);
        request.setValue(ip);
        request.setType("A");

        try {
            UpdateDomainRecordResponse response = client.getAcsResponse(request);
            System.out.println("IP更新成功："+new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            return false;
        }
        return true;
    }
}
